import React, { useCallback, useEffect, useState } from 'react';
import './Panel.css';
import { Button, Col, Flex, Modal, Row, Space, Statistic, Upload } from 'antd';
import LineChart from './LineChart';
import Icon from '../../containers/Icon/Icon';
import Tab = chrome.tabs.Tab;

async function getCurrentTab() {
  let queryOptions = { active: true, lastFocusedWindow: true };
  // `tab` will either be a `tabs.Tab` instance or `undefined`.
  let [tab] = await chrome.tabs.query(queryOptions);
  return tab;
}

async function getAllUserTabs() {
  const tabs = await chrome.tabs.query({ url: 'https://*/*' });
  return tabs;
}

function formatCurrentTime() {
  const date = new Date(); // 获取当前时间

  const year = date.getFullYear(); // 年
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月，注意月份是从0开始的
  const day = String(date.getDate()).padStart(2, '0'); // 日

  const hours = String(date.getHours()).padStart(2, '0'); // 小时
  const minutes = String(date.getMinutes()).padStart(2, '0'); // 分钟
  const seconds = String(date.getSeconds()).padStart(2, '0'); // 秒

  return `${year}${month}${day}_${hours}${minutes}${seconds}`;
}

const Panel: React.FC = () => {
  const [userTabs, setUserTabs] = useState<Tab[]>([]);
  const [currentTab, setCurrentTab] = useState<Tab | undefined>();
  const [data, setData] = useState<any[]>([]);
  const [state, setState] = useState<boolean>(false);

  useEffect(() => {
    const h = async () => {
      setUserTabs(await getAllUserTabs());
    };
    chrome.tabs.onCreated.addListener(h);
    chrome.tabs.onUpdated.addListener(h);
    chrome.tabs.onRemoved.addListener(h);
    h();
    return () => {
      chrome.tabs.onCreated.removeListener(h);
      chrome.tabs.onUpdated.removeListener(h);
      chrome.tabs.onRemoved.removeListener(h);
    };
  }, []);

  useEffect(() => {
    if (!currentTab) return;
    const h = (processes: any) => {
      if (!state) return;
      const time = new Date();
      let pCpu: any;
      let pGpu: any;
      Array.from(Object.values(processes)).forEach((p: any) => {
        if (p.type === 'gpu') {
          pGpu = p;
        }
        if (p.type === 'renderer' && p.tasks?.[0]?.tabId === currentTab.id) {
          pCpu = p;
        }
      });
      setData((data) => {
        return [
          ...data,
          {
            time,
            cpu: pCpu?.cpu ? Number(pCpu.cpu).toFixed(2) : 0,
            gpu: pGpu?.cpu ? Number(pGpu.cpu).toFixed(2) : 0,
            mem: ((pCpu?.jsMemoryUsed || 0) / 1024 / 1024).toFixed(3),
          },
        ];
      });
    };
    chrome.processes.onUpdated.addListener(h);
    return () => {
      chrome.processes.onUpdated.removeListener(h);
    };
  }, [currentTab, state]);

  const handleStateChange = useCallback(() => {
    setState((prevState) => !prevState);
  }, []);

  const handleRestart = useCallback(() => {
    setData(() => []);
    setState(() => true);
  }, []);

  // const handleClear = useCallback(() => {
  //   setData(() => []);
  // }, []);

  const handleExport = useCallback(() => {
    const blob = new Blob(
      [
        JSON.stringify(
          {
            type: 'application/cpumonitordata',
            version: 1,
            data,
          },
          null,
          2
        ),
      ],
      {
        type: 'application/json',
      }
    );
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = `cpu_monitor_${formatCurrentTime()}_${
      currentTab?.title
    }.json`;
    link.click();
  }, [data]);

  const handleImport = useCallback(async (file: File) => {
    const reader = new FileReader();
    reader.onload = () => {
      try {
        console.log('reader.result:', reader.result);
        const importJson = JSON.parse(reader.result as string);
        if (importJson.type !== 'application/cpumonitordata') {
          Modal.error({
            title: '导入错误',
            content: '数据格式无法识别',
          });
          return;
        }
        if (importJson.version > 1) {
          Modal.error({
            title: '导入错误',
            content: '当前扩展版本过低，请升级版本后重试',
          });
          return;
        }
        setState(() => false);
        setData(importJson.data);
      } catch (e) {
        Modal.error({
          title: '导入错误',
          content: '数据格式无法识别. ' + (e as any).message || '',
        });
      }
    };
    reader.readAsText(file);
  }, []);

  if (!currentTab) {
    return (
      <div
        style={{
          width: '100%',
          height: '100%',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
        }}
      >
        <Button
          type="primary"
          icon={<Icon type="record-start" />}
          onClick={async () => {
            const tab = await getCurrentTab();
            console.log('current tab:', tab);
            setCurrentTab(tab);
            setState(true);
            // setCurrentTabId((await getCurrentTab()).id)
          }}
        >
          开始记录CPU
        </Button>
      </div>
    );
  }

  return (
    <div>
      <Flex
        justify="space-between"
        style={{
          fontSize: 12,
          lineHeight: '32px',
          height: 32,
          background: '#dfdfdf',
        }}
      >
        <Space.Compact block>
          {state ? (
            <Button
              type="text"
              icon={<Icon type="record-stop" style={{ color: 'red' }} />}
              onClick={handleStateChange}
            >
              停止记录
            </Button>
          ) : (
            <Button
              type="text"
              icon={<Icon type="record-start" />}
              onClick={handleStateChange}
            >
              开始记录
            </Button>
          )}
          <Button
            onClick={handleRestart}
            type="text"
            icon={<Icon type="restart" />}
          >
            重新开始
          </Button>
          {/*<Button*/}
          {/*  onClick={handleClear}*/}
          {/*  type="text"*/}
          {/*  icon={<Icon type="clear" />}*/}
          {/*>*/}
          {/*  清除数据*/}
          {/*</Button>*/}
        </Space.Compact>
        <Space.Compact>
          <Button
            onClick={handleExport}
            type="text"
            icon={<Icon type="export" />}
          >
            导出数据
          </Button>
          <Upload
            maxCount={1}
            showUploadList={false}
            beforeUpload={handleImport}
          >
            <Button type="text" icon={<Icon type="import" />}>
              导入数据
            </Button>
          </Upload>
        </Space.Compact>
      </Flex>

      <div style={{ padding: 24 }}>
        <Row gutter={16}>
          <Col span={8}>
            <Statistic
              title="CPU"
              value={data.at(-1)?.cpu || 0}
              precision={2}
              suffix={'%'}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="GPU"
              value={data.at(-1)?.gpu || 0}
              precision={2}
              suffix={'%'}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="Memory"
              value={data.at(-1)?.mem || 0}
              precision={3}
              suffix={'MB'}
            />
          </Col>
        </Row>
        <div style={{ height: 400, width: '100%' }}>
          <LineChart data={data} />
        </div>
      </div>
    </div>
  );
};

export default Panel;
